package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/admin/product")
public class FileUploadController {

    @Value("${fileServer.url}")
    private String fileUrl;

    //1、文件上传
    @ApiOperation("文件上传")
    @RequestMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws IOException, MyException {
        //获取文件名
        String filename = file.getOriginalFilename();
        //获取文件
        byte[] bytes = file.getBytes();

        String path = ClassUtils.getDefaultClassLoader().getResource("tracker.conf").getPath();

        ClientGlobal.init(path);

        TrackerClient trackerClient = new TrackerClient();

        TrackerServer connection = trackerClient.getConnection();

        StorageClient1 storageClient1 = new StorageClient1(connection, null);

        //文件后缀名切割
        String extension = FilenameUtils.getExtension(filename);

        String image1 = storageClient1.upload_file1(bytes, extension, null);

        System.out.println(fileUrl + image1);
        return Result.ok(fileUrl + image1);
    }

}
